/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stcu.forms;

import stcu.*;
import stcu.robjects.*;
import java.io.*;
import java.util.*;
import java.net.*;
import com.nvlled.route.*;
import java.awt.event.*;


import javax.swing.*;
/**
 *
 * @author normal
 */
public class FileManagerForm extends javax.swing.JFrame {

    private JFrame self = this;
    private FileManager fileManager;
    private DefaultListModel<FileInfo> fileListModel;
    /**
     * Creates new form FileManagerForm
     */
    public FileManagerForm() {
        initComponents();
    }

    public FileManagerForm(FileManager fm) {
        initComponents();
        fileManager = fm;
        fileListModel = new DefaultListModel<FileInfo>();
        fileList.setModel(fileListModel);

        File currentDir = new File(fileManager.getFolderPath());
        pathText.setText(currentDir.getAbsolutePath());

        addListeners();
    }

    private void addListeners() {
        setFolderButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser(fileManager.getFolderPath());
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int ret = chooser.showOpenDialog(self);
                if (ret != JFileChooser.APPROVE_OPTION) {
                    return;
                }
                File dir = chooser.getSelectedFile();
                try {
                    String path = dir.getAbsolutePath();
                    fileManager.setFolder(path);
                    pathText.setText(path);
                } catch (IOException err) {
                    JOptionPane.showMessageDialog(self, err.getMessage());
                }
            }
        });
        downloadButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                FileInfo fileInfo = fileList.getSelectedValue();
                if (fileInfo == null) {
                    return;
                }

                try {
                    JFileChooser chooser = new JFileChooser(fileManager.getFolderPath());
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    int ret = chooser.showSaveDialog(self);
                    if (ret != JFileChooser.APPROVE_OPTION) {
                        return;
                    }
                    File destFile = chooser.getSelectedFile();
                    OutputStream out = new FileOutputStream(destFile);
                
                    InputStream fileInput = fileManager.download(fileInfo);
                    int count;
                    byte[] buffer = new byte[8192];
                    while ((count = fileInput.read(buffer)) > 0)
                    {
                        out.write(buffer, 0, count);
                        out.flush();
                    }
                    out.close();
                    fileInput.close();
                    JOptionPane.showMessageDialog(self, "Download finished: " + destFile);
                } catch (IOException err) {
                    err.printStackTrace();
                }
            }
        });
        fileManager.addListener(new FileManager.Listener() {
            public void fileAdded(final FileInfo file) {
                if (!fileListModel.contains(file)) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            fileListModel.addElement(file);
                            fileList.revalidate();
                        }
                    });
                }
            }

            public void fileRemoved(final FileInfo file) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        fileListModel.removeElement(file);
                    }
                });
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        fileList = new javax.swing.JList<FileInfo>();
        setFolderButton = new javax.swing.JButton();
        pathText = new javax.swing.JTextField();
        downloadButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);

        fileList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(fileList);

        setFolderButton.setText("Set Folder");

        pathText.setEditable(false);

        downloadButton.setText("Download");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(pathText, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(setFolderButton))
                    .addComponent(downloadButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setFolderButton)
                    .addComponent(pathText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(downloadButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FileManagerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FileManagerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FileManagerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FileManagerForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FileManagerForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected javax.swing.JButton downloadButton;
    protected javax.swing.JList<FileInfo> fileList;
    protected javax.swing.JScrollPane jScrollPane1;
    protected javax.swing.JTextField pathText;
    protected javax.swing.JButton setFolderButton;
    // End of variables declaration//GEN-END:variables
}
